package com.mvprxjavartrofit.ui.home;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

import com.mvprxjavartrofit.entity.User;

import java.util.ArrayList;
import java.util.List;

import static com.mvprxjavartrofit.entity.Const.uri;

/**
 * Created by Administrator
 * At 2016/10/20/17:26/2016
 * Project test
 */
public class HomeModel implements HomeContract.Model{

    private List<User> users = new ArrayList<>();


    @Override
    public boolean insert(ContentResolver resolver) {
        ContentValues values = new ContentValues();

        values.put("id", 22);
        values.put("name", "YYY");
        resolver.insert(uri, values);

        values.put("id", 33);
        values.put("name", "XXX");
        resolver.insert(uri, values);

        values.put("id", 44);
        values.put("name", "ZZZ");
        resolver.insert(uri, values);

        values.put("id", 55);
        values.put("name", "YYY");
        resolver.insert(uri, values);

        return true;
    }

    @Override
    public boolean query(ContentResolver resolver
            , String selection, String[] selectionArgs
            , ShowListener listener) {
        users.clear();
        Cursor cursor = resolver.query(uri, new String[]{"id", "name"}
                , selection, selectionArgs, "id asc");

        if(cursor != null) {
            while (cursor.moveToNext()){
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                Log.i("111", "id:" + id + " name:" + name);
                users.add(new User(id, name));
            }
        }
        if(cursor != null) {
            cursor.close();
        }

        listener.show(users);
        return true;
    }

    @Override
    public boolean delete(ContentResolver resolver
            , String selection, String[] selectionArgs) {
        resolver.delete(uri, selection, selectionArgs);

        return true;
    }

    @Override
    public boolean update(ContentResolver resolver, String selection, String[] selectionArgs) {
        ContentValues values = new ContentValues();

        values.put("id", 1234);
        values.put("name", "XYZ");
        resolver.update(uri, values, selection, selectionArgs);

        return true;
    }

}
